package com.xiaorong.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xiaorong.Principal;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	private static final String DEFAULT_LOGIN_URL = "/login.html";

	private String loginUrl = DEFAULT_LOGIN_URL;

	public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排
      
    public void setAllowUrls(String[] allowUrls) {  
        this.allowUrls = allowUrls;  
    }  
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");    
        if(null != allowUrls && allowUrls.length>=1) {
        	for(String url : allowUrls) {    
        		if(requestUrl.contains(url)) {    
        			return super.preHandle(request, response, handler);
        		}    
        	}  
        }
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		if (requestAttributes != null) {
			Principal principal = (Principal) request.getSession().getAttribute("adminUsername");
			if (principal == null) {
				response.sendRedirect(request.getContextPath() + loginUrl);
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}
	
}
